﻿using GN.Framework.Extensions;
using GN.Framework.Utils;
using StackExchange.Redis;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace GN.Pay.Core.Runtime.Caching.Impl
{
    /// <summary>
    /// 
    /// </summary>
    abstract class ARedisBase
    {
        /// <summary>
        ///  反序列化
        /// </summary>
        /// <param name="type"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        protected object Deserialize(Type type, RedisValue value)
        {
            if (DataConvertUtils.IsAllowTargetConvert(type))
            {
                return DataConvertUtils.TargetValueConvert(type, value.ToString());
            }
            if (type.Equals(typeof(byte[])))
            {
                return (byte[])value;
            }
            return value.ToString().JsonToObject(type, true);
        }

        /// <summary>
        /// 反序列化
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="value"></param>
        /// <returns></returns>
        protected T Deserialize<T>(RedisValue value)
        {
            if (!value.HasValue)
            {
                return default(T);
            }
            return (T)Deserialize(typeof(T), value);
        }

        /// <summary>
        /// 序列化
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        protected RedisValue Serialize(object value)
        {
            var type = value.GetType();
            if (DataConvertUtils.IsAllowTargetConvert(type))
            {
                return value.ToString();
            }
            if (type.Equals(typeof(byte[])))
            {
                return (byte[])value;
            }
            return value.ToJson(true);
        }
    }
}
